package com.csf.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.csf.fromwork.common.constant.GlobalConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 过滤器
 *
 * @author sss
 */

@Component
@Slf4j
public class AddUserId2HeaderFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==================> TokenConvertFilter");

        Long userId = null;

        try {
            // 取出当前登录的用户
            userId = StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            // 没有登录则放行
            return chain.filter(exchange);
        }

        log.info("## 当前登录的用户的ID:{}", userId);


        Long finalUserId = userId;
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header(GlobalConstants.USER_ID, String.valueOf(finalUserId))) // 将用户的ID设置到请求头中
                .build();
        return chain.filter(newExchange);
    }
}